<?php
#
# UNLVRandom: a dmBridge module for random objects
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class UNLVRandomCPController extends DMCPAdminController {

	public function index() {
		$this->preFlightCheck();
		$ds = UNLVRandomObject::getDataStore();

		if (DMHTTPRequest::getCurrent()->getMethod() == DMHTTPMethod::POST) {
			$flash = new DMFlash(
					DMLocalizedString::getString("NO_OBJECT_SELECTED"),
					false);
			$rep = DMHTTPRequest::getCurrent()->getRepresentation();
			if (is_array($rep->getFormValue("objects"))) {
				foreach ($rep->getFormValue("objects") as $obj) {
					$tmp = explode(DMAbstractForm::ALIAS_PTR_SEPARATOR, $obj);
					$col = DMCollectionFactory::getCollection(
							DMCollection::getSanitizedAlias($tmp[0]));
					$obj = DMObjectFactory::getObject($col, (int) $tmp[1]);
					$ds->deleteRandomObject($obj);
					$flash = new DMFlash(
							DMLocalizedString::getString(
									"RANDOM_OBJECT_DELETED",
									dirname(__FILE__) . "/../strings"),
							true);
				}
			}
			DMHTTPRequest::getCurrent()->getSession()->setFlash($flash);
			DMHTTPRequest::reload();
			die;
		}

		$this->tpl_vars['random_objects'] = $ds->getRandomObjects();

		$this->renderModuleTemplate(
					dirname(__FILE__) . "/../cp_templates/index.html.php");
		die;
	}

	public function add() {
		$this->preFlightCheck();

		$form = new UNLVRandomAddForm();
		$this->setForm($form);
		if (DMHTTPRequest::getCurrent()->getMethod() == DMHTTPMethod::POST) {
			$this->handleForm(DMLocalizedString::getString(
					"RANDOM_OBJECT_ADDED",
					dirname(__FILE__) . "/../strings"));
		}

		$this->tpl_vars['alias'] = $form->getFieldByName('alias')->getHTMLTag();
		$this->tpl_vars['ptr'] = $form->getFieldByName('ptr')->getHTMLTag();

		$this->renderModuleTemplate(
					dirname(__FILE__) . "/../cp_templates/add.html.php");
		die;
	}

}

